package me.numark.activities;

import com.tencent.mm.sdk.modelmsg.SendAuth;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.MainActivity;
import me.numark.R;
import me.numark.model.LogInResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

/**
 * Created by tian on 14-9-20:下午10:20.
 */
public class LogInActivity extends AuthenticatorActivity implements OnClickListener {

    @Bind(R.id.mobile_edit)
    EditText mobileEdit;

    @Bind(R.id.password_icon)
    ImageView passwordIcon;

    @Bind(R.id.password_edit)
    EditText passwordEdit;

    @Bind(R.id.forget_password)
    TextView forgetPassword;

    @Bind(R.id.log_in_button)
    Button logInButton;

    @Bind(R.id.register_button)
    Button registerButton;

    @Bind(R.id.qq_log_in_button)
    ImageView qqLogInButton;

    @Bind(R.id.weibo_log_in_button)
    ImageView weiboLogInButton;

    @Bind(R.id.weixin_log_in_button)
    ImageView weixinLogInButton;

    @Bind(R.id.close_btn)
    ImageView closeBtn;

    private boolean DEBUG = false;
    public static final String EXTRA_FROM_LOGIN = "from_login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_log_in;
        super.onCreate(savedInstanceState);
        if (DEBUG) {
            mobileEdit.setText("13910028267");
            passwordEdit.setText("tian1234");
        }
        forgetPassword.setOnClickListener(this);
        logInButton.setOnClickListener(this);
        registerButton.setOnClickListener(this);
        weiboLogInButton.setOnClickListener(this);
        qqLogInButton.setOnClickListener(this);
        weixinLogInButton.setOnClickListener(this);
        closeBtn.setOnClickListener(this);
        passwordIcon.setOnClickListener(this);
    }

    private boolean isInputValid() {
        return !TextUtils.isEmpty(mobileEdit.getText().toString()) && !TextUtils
                .isEmpty(passwordEdit.getText().toString());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.log_in_button:
                if (isInputValid()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("username", mobileEdit.getText().toString());
                    params.put("password", passwordEdit.getText().toString());
                    params.put("type", "1");
                    doLogin(params);
                }
                break;
            case R.id.weibo_log_in_button:
                mSsoHandler.authorize(this);
                break;
            case R.id.qq_log_in_button:
                if (mTencent == null) {
                    Utils.showToast(R.string.qq_not_installed);
                    return;
                }
                mTencent.login(this, "get_user_info", this);
                break;
            case R.id.weixin_log_in_button:
                if (Global.mWxApi.isWXAppInstalled() && Global.mWxApi.isWXAppSupportAPI()) {
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "none";
                    Global.mWxApi.sendReq(req);
                } else {
                    Utils.showToast(R.string.weixin_oauth_failed);
                }
                break;
            case R.id.register_button:
                startActivityForResult(new Intent(this, RegisterActivity.class), 0);
                break;
            case R.id.close_btn:
                finish();
                break;
            case R.id.forget_password:
                Intent intent = new Intent(LogInActivity.this,ModifyPasswdActivuty.class);
                intent.putExtra("fromLogin",true);
                startActivity(intent);
                break;
            case R.id.password_icon:
                passwordIcon.setSelected(!passwordIcon.isSelected());
                passwordEdit.setTransformationMethod(passwordIcon.isSelected() ?
                        SingleLineTransformationMethod.getInstance() :
                        PasswordTransformationMethod.getInstance());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case 0:
                //TODO
                break;
        }
    }

    @Override
    protected void afterLogin(int type, String uid, String token) {
        super.afterLogin(type, uid, token);
        Map<String, Object> params = new HashMap<>();
        params.put("username", uid);
        params.put("password", token);
        params.put("type", String.valueOf(type));
        doLogin(params);
    }

    void doLogin(final Map<String, Object> params) {
        new RequestServerTask<LogInResponse>(LogInResponse.class, this, getString(R.string.log_in_please_wait)) {
            @Override
            protected String requestServer() {
                return HttpUtil.post(NetworkConstants.LOG_IN_URL, params);
            }

            @Override
            protected void onSuccess(LogInResponse result) {
                saveUserInfo(result);
                if (result.data.status == Constants.REGISTER_COMPLETE) {
                    Intent intent = new Intent(LogInActivity.this, MainActivity.class);
                    startActivity(intent);
                }else if(result.data.status == Constants.PASSWORD_COMPLETE){
                    Intent intent = new Intent(LogInActivity.this, ChooseInterestsActivity.class);
                    intent.putExtra("user", Global.getGson().toJson(result.data));
                    intent.putExtra(EXTRA_FROM_LOGIN,true);
                    startActivity(intent);
                }else  if (result.data.status == Constants.INTEREST_COMPLETE){
                    Intent intent = new Intent(LogInActivity.this,AddFriendsActivity.class);
                    intent.putExtra(EXTRA_FROM_LOGIN,true);
                    startActivity(intent);
                }

                finish();
            }
        }
                .setDefaultErrMsg(R.string.log_in_failed)
                .start();
    }

    @Override
    protected void saveUserInfo(LogInResponse result) {
        super.saveUserInfo(result);
        Settings.setCurrentUid(result.data.uid);
        LocalBroadcastManager.getInstance(getBaseContext())
                .sendBroadcast(new Intent(Constants.ACTION_USER_CHANGED));
    }
}
